<style lang="less">
    @import "userManage.less";
</style>
<template>
    <div class="search">
        <Row>
            <Col>
                <Card>
                    <Row>
                        <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
                            <Form-item label="登录名" prop="username">
                                <Input type="text" v-model="searchForm.username" clearable placeholder="请输入登录名"
                                       style="width: 200px"/>
                            </Form-item>
                            <Form-item label="部门" prop="deptId">
                                <Cascader v-model="selectDep" :data="department" :load-data="loadData"
                                          @on-change="handleChangeDep" change-on-select filterable
                                          placeholder="请选择或输入搜索部门" style="width: 200px;padding-top: 5px"></Cascader>
                            </Form-item>
                            <span v-if="drop">
                            <Form-item label="手机号" prop="phone">
                              <Input type="text" v-model="searchForm.phone" clearable placeholder="请输入手机号"
                                     style="width: 200px"/>
                            </Form-item>
                              <Form-item label="邮箱" prop="userEmail">
                                <Input type="text" v-model="searchForm.userEmail" clearable placeholder="请输入邮箱"
                                       style="width: 200px"/>
                              </Form-item>
                              <Form-item label="用户状态" prop="lockFlag">
                                <Select v-model="searchForm.lockFlag" placeholder="请选择" clearable style="width: 200px">
                                  <Option value="0">正常</Option>
                                  <Option value="9">锁定</Option>
                                </Select>
                              </Form-item>
                              <Form-item label="创建时间">
                                <DatePicker v-model="selectDate" type="daterange" format="yyyy-MM-dd" clearable
                                            @on-change="selectDateRange" placeholder="选择起始时间"
                                            style="width: 200px"></DatePicker>
                              </Form-item>
                            </span>
                            <Form-item style="margin-left:-35px;" class="br">
                                <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                <Button @click="handleReset">重置</Button>
                                <a class="drop-down" @click="dropDown">{{dropDownContent}}
                                    <Icon :type="dropDownIcon"></Icon>
                                </a>
                            </Form-item>
                        </Form>
                    </Row>
                    <Row class="operation" style="margin-bottom: 2vh;">
                        <Button @click="add" type="primary" icon="md-add">添加用户</Button>
                        <Button @click="delAll" icon="md-trash">批量删除</Button>
                        <Button @click="getUserList" icon="md-refresh">刷新</Button>
                        <circleLoading v-if="operationLoading"/>
                    </Row>
                    <Row>
                        <Alert show-icon>
                            已选择 <span class="select-count">{{selectCount}}</span> 项
                            <a class="select-clear" @click="clearSelectAll">清空</a>
                        </Alert>
                    </Row>
                    <Row>
                        <Table :loading="loading" border :columns="columns" :data="data" sortable="custom"
                               @on-sort-change="changeSort" @on-selection-change="showSelect" ref="table">
                            <template slot-scope="{ row, index }" slot="lockFlag">
                                <div v-if="row.lockFlag === '0'">
                                    <Tag color="success" size="default">启用</Tag>
                                </div>
                                <div v-else>
                                    <Tag color="error" size="default">禁用</Tag>
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="action">
                                <Button style="margin-right:5px" type="primary" size="small" @click="edit(row)">编辑
                                </Button>
                                <Button v-if="row.lockFlag==='0'" style="margin-right:5px" type="warning" size="small"
                                        @click="disable(row)">禁用
                                </Button>
                                <Button v-if="row.lockFlag==='9'" style="margin-right:5px" type="success" size="small"
                                        @click="enable(row)">启用
                                </Button>
                                <Button v-if="row.passErrorCount>0" style="margin-right:5px" type="success" size="small"
                                        @click="resetFailCount(row)">重置登录次数
                                </Button>
                                <Button v-has="'user_pass_reset'" style="margin-right:5px" type="warning" size="small"
                                        @click="resetPass(row)">重置密码
                                </Button>
                                <Button type="error" size="small" @click="remove(row)">删除</Button>
                            </template>
                        </Table>
                    </Row>
                    <Row type="flex" justify="end" class="page">
                        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
                              @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]"
                              size="small" show-total show-elevator show-sizer></Page>
                    </Row>
                </Card>
            </Col>
        </Row>
        <Modal :title="modalTitle" v-model="userModalVisible" :mask-closable='false' :width="500"
               :styles="{top: '90px'}">
            <Form ref="userForm" :model="userForm" :label-width="70" :rules="userFormValidate">
                <FormItem label="登录名" prop="username">
                    <Input v-model="userForm.username" :disabled="modalType===1" autocomplete="off"/>
                </FormItem>
                <FormItem label="真实姓名" prop="userRealName">
                    <Input v-model="userForm.userRealName" autocomplete="off"/>
                </FormItem>
                <FormItem label="密码" prop="password" v-if="modalType===0" :error="errorPass">
                    <Input type="afspassword" password v-model="userForm.password" autocomplete="off"/>
                </FormItem>
                <FormItem label="邮箱" prop="userEmail">
                    <Input v-model="userForm.userEmail"/>
                </FormItem>
                <FormItem label="手机号" prop="phone">
                    <Input v-model="userForm.phone"/>
                </FormItem>

                <Form-item label="所属部门" prop="departmentTitle">
                    <Poptip trigger="click" placement="right" title="选择部门" width="250" @on-popper-show="searchDp">
                        <div style="display:flex;">
                            <Input v-model="userForm.departmentTitle" readonly style="margin-right:10px;"/>
                            <Button icon="md-trash" @click="clearSelectDep">清空已选</Button>
                        </div>
                        <div slot="content" class="tree-bar">
                            <Input v-model="searchKey" suffix="ios-search" @on-change="searchDp" placeholder="输入部门名搜索"/>
                            <Tree :data="dataDep" :load-data="loadDataTree" @on-select-change="selectTree"></Tree>
                            <Spin size="large" fix v-if="dpLoading"></Spin>
                        </div>
                    </Poptip>
                </Form-item>
                <FormItem label="角色分配" prop="roleIds">
                    <Select v-model="userForm.roleIds" multiple>
                        <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.roleName">
                            <span style="margin-right:5px;">{{ item.roleName }}</span>
                            <span>{{ item.roleCode }}</span>
                        </Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelUser">取消</Button>
                <Button type="primary" :loading="submitLoading" @click="submitUser">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {
        getUserListData,
        addUser,
        editUser,
        enableUser,
        disableUser,
        deleteUser,
        getAllUserData,
        resetFailCount,
        resetPassWord
    } from "@/projects/basic/api/admin/user";
    import {
        initDepartment,
        loadDepartment,
        searchDepartment
    } from "@/projects/basic/api/admin/department";

    import {
        getAllRoleList
    } from "@/projects/basic/api/admin/role";
    import circleLoading from "_c/circle-loading/circle-loading.vue";

    export default {
        name: "user-manage",
        components: {
            circleLoading
        },
        data() {
            const validatePassword = (rule, value, callback) => {
                if (value.length < 6) {
                    callback(new Error("密码长度不得小于6位"));
                } else {
                    callback();
                }
            };
            const validateMobile = (rule, value, callback) => {
                let reg = /^[1][0-9]{10}$/;
                if (!reg.test(value)) {
                    callback(new Error("手机号格式错误"));
                } else {
                    callback();
                }
            };
            return {
                loading: true,
                dpLoading: false, // 部门树加载
                operationLoading: false,
                importLoading: false,
                loadingExport: true,
                drop: false,
                dropDownContent: "展开",
                dropDownIcon: "ios-arrow-down",
                selectCount: 0,
                selectList: [],
                viewImage: false,
                deptId: [],
                selectDep: [],
                department: [],
                dataDep: [],
                searchKey: "",
                searchForm: {
                    username: "",
                    deptId: "",
                    phone: "",
                    userEmail: "",
                    lockFlag: "",
                    pageNumber: 1,
                    pageSize: 10,
                    startDate: "",
                    endDate: ""
                },
                selectDate: null,
                modalType: 0,
                userModalVisible: false,
                modalTitle: "",
                userForm: {
                    sex: 1,
                    type: 0,
                    username:'',
                    password:'',
                    avatar: "https://s1.ax1x.com/2018/05/19/CcdVQP.png",
                    roleIds: [],
                    deptId: "",
                    departmentTitle: "",
                    userRealName: "",
                    userEmail: "",
                    phone: "",

                },
                userRoles: [],
                roleList: [],
                errorPass: "",
                userFormValidate: {
                    username: [
                        {required: true, message: "账号不能为空", trigger: "blur"}
                    ],
                    userRealName: [
                        {required: true, message: "用户名不能为空", trigger: "blur"}
                    ],
                    phone: [
                        {required: true, message: "手机号不能为空", trigger: "blur"},
                        {validator: validateMobile, trigger: "blur"}
                    ],
                    userEmail: [
                        {required: true, message: "请输入邮箱地址"},
                        {type: "email", message: "邮箱格式不正确"}
                    ],
                    password: [
                        {required: true, message: "密码不能为空", trigger: "blur"},
                        {validator: validatePassword, trigger: "blur"}
                    ]
                },
                submitLoading: false,
                columns: [
                    {
                        type: "selection",
                        minWidth: 60,
                        maxWidth:60,
                        align: "center",
                        fixed: "left"
                    },
                    {
                        title: "登录名",
                        key: "username",
                        minWidth: 120,
                        fixed: "left"
                    },
                    {
                        title: "真实姓名",
                        key: "userRealName",
                        minWidth: 145,
                        fixed: "left",
                        ellipsis: true,
                        tooltip: true
                    },
                    {
                        title: "所属部门",
                        key: "departmentTitle",
                        width: 120,
                        tooltip: true
                    },
                    {
                        title: "手机",
                        key: "phone",
                        minWidth: 115
                    },{
                        title: "登录失败次数",
                        key: "passErrorCount",
                        minWidth: 140
                    },
                    {
                        title: "邮箱",
                        key: "userEmail",
                        minWidth: 180
                    },
                    {
                        title: "状态",
                        key: "lockFlag",
                        align: "center",
                        minWidth: 140,
                        slot: "lockFlag"
                    },
                    {
                        title: "创建时间",
                        key: "createTime",
                        sortable: true,
                        minWidth: 150
                    },
                    {
                        title: "操作",
                        key: "action",
                        minWidth: 300,
                        align: "center",
                        fixed: "right",
                        slot: "action"
                    }
                ],
                data: [],
                total: 0
            };
        },
        methods: {
            init() {
                this.initDepartmentData();
                this.getUserList();
                this.initDepartmentTreeData();
            },
            initDepartmentData() {
                let self = this;
                initDepartment().then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.label;
                                e.disabled = true;
                            }
                            if(e.id===self.userForm.deptId ){
                                e.selected = true;
                            }
                        });
                        this.department = res.data;
                    }
                });
            },
            initDepartmentTreeData() {
                let self = this;
                initDepartment().then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                            if(e.id===self.userForm.deptId ){
                                e.selected = true;
                            }
                        });
                        this.dataDep.splice(0,this.dataDep.length);
                        this.dataDep.push(...res.data);
                    }
                });
            },
            loadData(item, callback) {
                item.loading = true;
                loadDepartment(item.value).then(res => {
                    item.loading = false;
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.label;
                                e.disabled = true;
                            }
                        });
                        item.children = res.data;
                        callback();
                    }
                });
            },
            loadDataTree(item, callback) {
                let self = this;
                loadDepartment(item.id).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                            if(e.id===self.userForm.deptId ){
                                e.selected = true;
                            }
                        });

                        callback(res.data);
                    }
                });
            },
            searchDp() {
                // 搜索部门
                if (this.searchKey) {
                    this.dpLoading = true;
                    let self = this;
                    searchDepartment({title: this.searchKey}).then(res => {
                        this.dpLoading = false;
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            if(e.id===self.userForm.deptId ){
                                e.selected = true;
                            }
                            this.dataDep.splice(0,this.dataDep.length);
                            this.dataDep.push(...res.data);
                        }
                    });
                } else {
                    this.initDepartmentTreeData();
                }
            },
            selectTree(v) {
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    this.userForm.deptId = data.id;
                    this.userForm.departmentTitle = data.title;
                }
            },
            clearSelectDep() {
                this.userForm.deptId = "";
                this.userForm.departmentTitle = "";
            },
            handleChangeDep(value, selectedData) {
                // 获取最后一个值
                if (value && value.length > 0) {
                    this.searchForm.deptId = value[value.length - 1];
                } else {
                    this.searchForm.deptId = "";
                }
            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getUserList();
                this.clearSelectAll();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getUserList();
            },
            selectDateRange(v) {
                if (v) {
                    this.searchForm.startDate = v[0];
                    this.searchForm.endDate = v[1];
                }
            },
            getUserList() {
                // 多条件搜索用户列表
                this.loading = true;
                getUserListData(this.searchForm).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        this.data = res.data.records;
                        this.total = res.data.total;
                    }
                });
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getUserList();
            },
            handleReset() {
                this.$refs.searchForm.resetFields();
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.selectDate = null;
                this.searchForm.startDate = "";
                this.searchForm.endDate = "";
                this.selectDep = [];
                this.searchForm.deptId = "";
                // 重新加载数据
                this.getUserList();
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getUserList();
            },
            getRoleList() {
                getAllRoleList().then(res => {
                    if (res.code === "0000") {
                        this.roleList = res.data;
                    }
                });
            },
            cancelUser() {
                this.userModalVisible = false;
            },
            submitUser() {
                this.$refs.userForm.validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            // 添加用户 避免编辑后传入id
                            delete this.userForm.userId;
                            delete this.userForm.status;
                            if (
                                this.userForm.password == "" ||
                                this.userForm.password == undefined
                            ) {
                                this.errorPass = "密码不能为空";
                                return;
                            }
                            if (this.userForm.password.length < 6) {
                                this.errorPass = "密码长度不得少于6位";
                                return;
                            }
                            this.submitLoading = true;
                            addUser(this.userForm).then(res => {
                                this.submitLoading = false;
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.getUserList();
                                    this.userModalVisible = false;
                                }
                            }).catch(() => {
                                this.submitLoading = false;
                            });
                        } else {
                            // 编辑
                            this.submitLoading = true;
                            editUser(this.userForm).then(res => {
                                this.submitLoading = false;
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.getUserList();
                                    this.userModalVisible = false;
                                }
                            }).catch(() => {
                                this.submitLoading = false;
                            });
                        }
                    }
                });
            },
            add() {
                this.modalType = 0;
                this.modalTitle = "添加用户";
                this.userForm.userId = "";
                this.$refs.userForm.resetFields();
                this.userModalVisible = true;
                this.userForm.deptId='';
                this.userForm.departmentTitle='';
                delete this.userForm.createTime;
                delete this.userForm.updateTime;
            },
            edit(v) {
                this.modalType = 1;
                this.modalTitle = "编辑用户";
                this.$refs.userForm.resetFields();
                // 转换null为""
                for (let attr in v) {
                    if (v[attr] === null) {
                        v[attr] = "";
                    }
                }
                let str = JSON.stringify(v);
                let userInfo = JSON.parse(str);

                this.userForm = userInfo;
                let selectRolesId = [];
                this.userForm.roles.forEach(function (e) {
                    selectRolesId.push(e.id);
                });
                delete this.userForm.permissions;
                delete this.userForm.roles;
                delete this.userForm.roles;
                this.userForm.roleIds = selectRolesId;
                this.userModalVisible = true;
            },
            enable(v) {
                this.$Modal.confirm({
                    title: "确认启用",
                    content: "您确认要启用用户 " + v.username + " ?",
                    onOk: () => {
                        this.operationLoading = true;
                        enableUser(v.userId).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.getUserList();
                            }
                        });
                    }
                });
            },
            resetFailCount(v) {
                this.$Modal.confirm({
                    title: "确认重置",
                    content: "您确认重置用户 " + v.username + "  登录失败次数?",
                    onOk: () => {
                        this.operationLoading = true;
                        resetFailCount(v.userId).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.getUserList();
                            }
                        });
                    }
                });
            },
            resetPass(v) {
                this.$Modal.confirm({
                    title: "确认重置",
                    content: "您确认重置用户 " + v.username + "  密码",
                    onOk: () => {
                        this.operationLoading = true;
                        resetPassWord(v.userId).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.getUserList();
                            }
                        });
                    }
                });
            },
            disable(v) {
                this.$Modal.confirm({
                    title: "确认禁用",
                    content: "您确认要禁用用户 " + v.username + " ?",
                    onOk: () => {
                        this.operationLoading = true;
                        disableUser(v.userId).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.getUserList();
                            }
                        });
                    }
                });
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除用户 " + v.username + " ?",
                    onOk: () => {
                        this.operationLoading = true;
                        deleteUser(v.userId).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.getUserList();
                            }
                        });
                    }
                });
            },
            dropDown() {
                if (this.drop) {
                    this.dropDownContent = "展开";
                    this.dropDownIcon = "ios-arrow-down";
                } else {
                    this.dropDownContent = "收起";
                    this.dropDownIcon = "ios-arrow-up";
                }
                this.drop = !this.drop;
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            clearSelectAll() {
                this.$refs.table.selectAll(false);
            },
            delAll() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.userId + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        deleteUser(ids).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.clearSelectAll();
                                this.getUserList();
                            }
                        });
                    }
                });
            }
        },
        mounted() {
            this.init();
            this.getRoleList();
        }
    };
</script>
